package cn.b.sky.mes.mm.service.impl;

import java.util.List;

import cn.b.sky.mes.mm.dao.WCMessageConfigDao;
import cn.b.sky.mes.mm.dao.WUMessageConfigDao;
import cn.b.sky.mes.mm.service.MessageConfigService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.b.sky.mes.mm.model.MessageConfig;
import cn.b.sky.mes.mm.model.condition.MessageConfigCondition;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.Page;
import cn.b.sky.common.utils.DatabaseUtils;
import cn.b.sky.i18n.utils.LocaleResourceBundle;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.service.model.User;

/**
 * 
 * <strong>Title : MessageConfigServiceImpl.java<br></strong>
 * <strong>Package : cn.b.sky.mes.mm.service.impl<br></strong>
 * <strong>Description : </strong> 消息配置业务实现类<br> 
 * <strong>Create on : 2016年9月10日 下午1:22:31<br></strong>
 * <p>
 * @author dapeng.li<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人|修改日期|修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
@Service("messageConfigService")
public class MessageConfigServiceImpl implements MessageConfigService {

  private static final Logger LOG = LoggerFactory.getLogger(MessageConfigServiceImpl.class);

  /**
   * 工作中心接口
   */
  @Autowired
  private WCMessageConfigDao wCMessageConfigDao;

  /**
   * 作业单元接口
   */
  @Autowired
  private WUMessageConfigDao wUMessageConfigDao;

  @Override
  public Page getMsgConfigsByCondition(MessageConfigCondition condition) {
    // 工作中心
    if (!StringUtils.isEmpty(condition.getWorkcenterCode()) && StringUtils.isEmpty(condition.getWorkunitCode())) {
      condition.setData(wCMessageConfigDao.getMsgConfigsByCondition(condition));
      condition.setTotalCount(wCMessageConfigDao.getMsgConfigsCountByCondition(condition));
    } else if (StringUtils.isEmpty(condition.getWorkcenterCode())
        && !StringUtils.isEmpty(condition.getWorkunitCode())) {
      condition.setData(wUMessageConfigDao.getMsgConfigsByCondition(condition));
      condition.setTotalCount(wUMessageConfigDao.getMsgConfigsCountByCondition(condition));
    }
    return condition;
  }

  @Override
  public MessageConfig getMessageConfig(MessageConfig messageConfig) {
    if (!StringUtils.isEmpty(messageConfig.getWorkcenterCode())) {
      return wCMessageConfigDao.getMessageConfig(messageConfig);
    } else if (!StringUtils.isEmpty(messageConfig.getWorkunitCode())) {
      return wUMessageConfigDao.getMessageConfig(messageConfig);
    }
    return null;
  }

  @Override
  public void saveMessageConfig(MessageConfig messageConfig) {
    saveMsgConfig(messageConfig);
  }

  @Override
  public void saveMessageConfig(List<MessageConfig> messageConfigs) {
    for (MessageConfig messageConfig : messageConfigs) {
      saveMsgConfig(messageConfig);
    }
  }

  private void saveMsgConfig(MessageConfig msgConfig) {
    if (!StringUtils.isEmpty(msgConfig.getWorkcenterCode())) {
      if (null == msgConfig.getId() || 0 == msgConfig.getId()) {
        wCMessageConfigDao.inertMessageConfig(msgConfig);
        for (User user : msgConfig.getReceivers()) {
          wCMessageConfigDao.insertMessageUser(msgConfig.getSiteCode(), msgConfig.getId(), user.getUserCode());
        }
      } else {
        wCMessageConfigDao.updateMessageConfig(msgConfig);
        wCMessageConfigDao.deleteMessageUserById(msgConfig.getId());
        for (User user : msgConfig.getReceivers()) {
          wCMessageConfigDao.insertMessageUser(msgConfig.getSiteCode(), msgConfig.getId(), user.getUserCode());
        }
      }
    } else if (!StringUtils.isEmpty(msgConfig.getWorkunitCode())) {
      if (null == msgConfig.getId() || 0 == msgConfig.getId()) {
        wUMessageConfigDao.inertMessageConfig(msgConfig);
        for (User user : msgConfig.getReceivers()) {
          wUMessageConfigDao.insertMessageUser(msgConfig.getSiteCode(), msgConfig.getId(), user.getUserCode());
        }
      } else {
        wUMessageConfigDao.updateMessageConfig(msgConfig);
        wUMessageConfigDao.deleteMessageUserById(msgConfig.getId());
        for (User user : msgConfig.getReceivers()) {
          wUMessageConfigDao.insertMessageUser(msgConfig.getSiteCode(), msgConfig.getId(), user.getUserCode());
        }
      }
    }
  }

  @Override
  public BatchJobReport deleteMessageConfig(MessageConfig messageConfig) {
    if (null != messageConfig) {
      String message = messageConfig.getStrategyText();
      String cause = "";
      boolean success = true;
      try {
        if (!StringUtils.isEmpty(messageConfig.getWorkcenterCode())) {
          // 删除收信人
          wCMessageConfigDao.deleteMessageUserById(messageConfig.getId());
          // 删除配置
          wCMessageConfigDao.deleteMessageConfigById(messageConfig.getId());
        } else if (!StringUtils.isEmpty(messageConfig.getWorkunitCode())) {
          // 删除收信人
          wUMessageConfigDao.deleteMessageUserById(messageConfig.getId());
          // 删除配置
          wUMessageConfigDao.deleteMessageConfigById(messageConfig.getId());
        }
      } catch (Exception e) {
        LOG.error("{}", e);
        success = false;
        String errorMsg = e.getMessage();
        if (DatabaseUtils.isConstraintsError(errorMsg)) {
          //外键删除已存在提示
          errorMsg = LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
              SecurityContextUtil.getLanguageCode(), "dataBaseOperationPkFail.M")
              + LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
                  SecurityContextUtil.getLanguageCode(), "notDelete.M");
        }
        cause = errorMsg;
      }
      return new BatchJobReport(message, cause, success);
    } else {
      return new BatchJobReport("", "Message config is not existing.", false);
    }
  }

  @Override
  public MessageConfig getMessageConfigById(Long id, boolean isWorkcenter) {
    if (isWorkcenter) {
      return wCMessageConfigDao.getMessageConfigById(id);
    } else {
      return wUMessageConfigDao.getMessageConfigById(id);
    }
  }

}
